<?php 
session_start();
error_reporting(0);
include('includes/connection.php');

// Fetch grouped warehose items
$sql = "SELECT id_item, itemid, SUM(quantity) AS total_qty 
        FROM warehouse_stock 
        GROUP BY  itemid";
$query = $dbh->prepare($sql);
$query->execute();
$items = $query->fetchAll(PDO::FETCH_ASSOC);

// Handle goods issue form
$message = '';
if (isset($_POST['issue'])) {

     //echo "<pre>";
    //print_r($_POST);
    //echo "</pre>";

    $itemid = intval($_POST['itemid']);
    $issue_qty = intval($_POST['issue_qty']);
    $remarks = trim($_POST['remarks']);
    $issued_by = $_SESSION['username'] ?? 'system';

    // Fetch available stock rows (FIFO order)
    $sql = "SELECT * FROM warehouse_stock 
            WHERE itemid = :itemid AND quantity > 0 
            ORDER BY regdate ASC";
    $query = $dbh->prepare($sql);
    $query->bindParam(':itemid', $itemid);
    $query->execute();
    $rows = $query->fetchAll(PDO::FETCH_ASSOC);

    $remaining = $issue_qty;

    foreach ($rows as $row) {
        if ($remaining <= 0) break;

        $stock_id = $row['id'];
        $available = $row['quantity'];

        $deduct = min($remaining, $available);
        $new_qty = $available - $deduct;

        // Update stock
        $update = $dbh->prepare("UPDATE warehouse_stock SET quantity = :new_qty WHERE id = :id");
        $update->bindParam(':new_qty', $new_qty);
        $update->bindParam(':id', $stock_id);
        $update->execute();

        // Log issue
        $insert = $dbh->prepare("INSERT INTO warehouse_issue 
            (id_item, itemid, issue_quantity, remarks, issued_by) 
            VALUES (:id_item, :itemid, :issue_qty, :remarks, :issued_by)");
        $insert->bindParam(':id_item', $row['id_item']);
        $insert->bindParam(':itemid', $itemid);
        $insert->bindParam(':issue_qty', $deduct);
        $insert->bindParam(':remarks', $remarks);
        $insert->bindParam(':issued_by', $issued_by);
        $insert->execute();

        $remaining -= $deduct;
    }

    //Prepare message
    if ($remaining > 0) {
        $message = "<p style='color:red;'>Partial issue done. Only some quantity was available.</p>";
   } else {
        $message = "<p style='color:green;'>Goods issued successfully.</p>";
        //if (!$query->execute()) {
//$errorInfo = $query->errorInfo();
    //echo "<p style='color:red;'>Query Error: {$errorInfo[2]}</p>";
}
   }
    

?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Goods Issue</title>
    <link rel="stylesheet" type="text/css" href="assets/css/style1.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        form {
            margin-top: 20px;
            padding: 20px;
            background: #f4f4f4;
            border-radius: 8px;
            max-width: 500px;
        }
        label {
            display: block;
            margin-top: 10px;
            font-weight: bold;
        }
        select, input[type="number"], input[type="text"] {
            width: 100%;
            padding: 8px;
            margin-top: 4px;
            border-radius: 4px;
            border: 1px solid #ccc;
        }
        button {
            margin-top: 15px;
            padding: 10px 20px;
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
        .message {
            margin-top: 15px;
        }
    </style>
</head>
<body>

<?php include('includes/header.php'); ?>

<h3>📦 Goods Issue Form</h3>

<form method="post">
    <label for="itemid">Select Item:</label>
    <select name="itemid" id="itemid" required>
        <option value="">-- Choose an item --</option>
        <?php foreach ($items as $item): ?>
            <option value="<?= $item['itemid'] ?>">
                Item <?= $item['itemid'] ?> - Total Qty: <?= $item['total_qty'] ?>
            </option>
        <?php endforeach; ?>
    </select>

    <label for="issue_qty">Issue Quantity:</label>
    <input type="number" name="issue_qty" id="issue_qty" min="1" required>

    <label for="remarks">Remarks (optional):</label>
    <input type="text" name="remarks" id="remarks" placeholder="Enter remarks">

    <button type="submit" name="issue">✅ Issue Now</button>
</form>

<?php if (isset($_POST['issue']) && !empty($message)): ?>
    <div class="message">
        <?= $message ?>
    </div>
<?php endif; ?>

<?php include('includes/footer.php'); ?>
</body>
</html>
